<script lang="ts" setup>
import { useCartStore, type CartItem } from '@/store/modules/cart';
import { useImage } from '@/hooks';
import Taro from '@tarojs/taro';
import { useAuthStore } from '@/store';
import { storeToRefs } from 'pinia';
import { onMounted } from 'vue';

definePageConfig({
  navigationBarTitleText: '购物车',
});

const cartStore = useCartStore();
const { nurseUser } = storeToRefs(useAuthStore());

const updateQuantity = (item: CartItem, change: number) => {
  const newQuantity = item.quantity + change;
  cartStore.updateItemQuantity(item.id, newQuantity);
};

const confirmRemove = (itemId: number | string) => {
  Taro.showModal({
    title: '确认',
    content: '确定要删除这个商品吗？',
    success: (res) => {
      if (res.confirm) {
        cartStore.removeFromCart(itemId);
      }
    }
  });
};

const removeFromCart = (itemId: number | string) => {
  cartStore.removeFromCart(itemId);
};

const toggleSelection = (itemId: number | string) => {
    cartStore.toggleItemSelection(itemId);
};

const toggleSelectAll = () => {
    cartStore.toggleSelectAll(!cartStore.areAllSelected);
}

const handleQuantityChange = (item: CartItem, quantity: number) => {
  cartStore.updateItemQuantity(item.id, quantity);
};

const checkout = async () => {
  const selectedItems = [...cartStore.selectedItems];
  if (selectedItems.length === 0) {
    Taro.showToast({
      title: '请先选择商品',
      icon: 'none'
    });
    return;
  }

  // 跳转到订单确认页面，传递购物车商品信息
  const cartData = {
    items: selectedItems,
    totalPrice: cartStore.totalPrice,
    totalItems: cartStore.totalItems
  };
  
  // 将购物车数据存储到本地存储中
  Taro.setStorageSync('cart_checkout_data', cartData);
  
  // 跳转到订单确认页面
  Taro.navigateTo({
    url: `/package/goodspay/index?fromCart=true`
  });
};

async function doPay(payInfo: any, itemsToRemove: CartItem[]){
    const { timestamp, noncestr, package: packAge, sign } = payInfo;

    Taro.requestPayment({
        timeStamp: timestamp,
        nonceStr: noncestr,
        package: packAge,
        paySign: sign,
        signType: 'RSA',
        fail: () => {
            // handle fail
        },
        complete() {
            // handle complete
        },
        success: res => {
            if (res.errMsg == 'requestPayment:ok') {
                Taro.showToast({
                    title: '支付成功！',
                    icon: 'success',
                    duration: 1500
                });
                // Here you might want to clear selected items from cart
                itemsToRemove.forEach(item => cartStore.removeFromCart(item.id));
            }
        }
    });
}

const goShopping = () => {
    Taro.switchTab({
        url: '/pages/shop/shop'
    })
}

// 检查是否有需要清除的购物车商品（支付成功后）
onMounted(() => {
    const itemsToRemove = Taro.getStorageSync('clear_cart_items');
    if (itemsToRemove && Array.isArray(itemsToRemove)) {
        itemsToRemove.forEach(itemId => {
            cartStore.removeFromCart(itemId);
        });
        // 清除存储的标记
        Taro.removeStorageSync('clear_cart_items');
    }
});
</script>

<template>
  <view class="flex flex-col w-full h-screen bg-gray-100 font-sans" :style="{ paddingBottom: '100rpx' }">
    <view v-if="!cartStore || cartStore.items.length === 0" class="flex-1 flex flex-col items-center justify-center text-gray-400 -mt-[100rpx]">
      <view class="text-[100rpx] i-mdi-cart-off opacity-50"></view>
      <text class="mt-[30rpx] text-[32rpx] mb-[80rpx]">购物车还是空的</text>
      <nut-button @tap="goShopping">去逛逛</nut-button>
    </view>
    <template v-else>
      <scroll-view :scroll-y="true" class="flex-1">
        <view class="p-[24rpx]">
            <view class="bg-white rounded-[20rpx] p-[24rpx]">
            <view v-for="(item, index) in cartStore.items" :key="item.id" 
                    class="flex items-center py-[24rpx]"
                    :class="{ 'border-b border-gray-100': index < cartStore.items.length - 1 }">
                
                <!-- Custom Checkbox -->
                <view @tap.stop="toggleSelection(item.id)" class="w-[40rpx] h-[40rpx] rounded-full border-2 flex items-center justify-center mr-[24rpx] flex-shrink-0"
                    :class="item.selected ? 'bg-green-500 border-green-500' : 'border-gray-300'">
                <view v-if="item.selected" class="i-mdi-check text-white text-[28rpx]"></view>
                </view>

                <image :src="useImage(item.pic || '')" class="w-[160rpx] h-[160rpx] rounded-[16rpx] bg-gray-200 flex-shrink-0" />
                
                <view class="flex-1 flex flex-col justify-start ml-[24rpx] self-start overflow-hidden">
                    <view class="text-[28rpx] text-gray-800 leading-tight truncate">{{ item.typeName }}</view>
                    <view class="flex justify-between items-center mt-[auto]">
                        <view class="text-[32rpx] font-bold text-red-500">¥{{ item.price }}</view>
                    </view>
                </view>

                <!-- Quantity controls -->
                <view class="flex items-center gap-[4rpx] bg-gray-100 rounded-full ml-[20rpx] flex-shrink-0">
                    <nut-input-number :model-value="item.quantity" @change="v => handleQuantityChange(item, v)" min="1"/>
                </view>

                <!-- Delete Button -->
                <view class="i-mdi-delete text-gray-400 text-[44rpx] ml-[24rpx] flex-shrink-0" @tap="confirmRemove(item.id)"></view>
            </view>
            </view>
        </view>
      </scroll-view>
      
      <!-- Footer -->
      <view class="h-[140rpx] bg-white border-t border-gray-200 flex items-center justify-between px-[30rpx] fixed bottom-[100rpx] left-0 right-0 safe-area-bottom">
        <view class="flex items-center" @tap="toggleSelectAll">
            <view class="w-[40rpx] h-[40rpx] rounded-full border-2 flex items-center justify-center mr-[16rpx]"
                  :class="cartStore.areAllSelected ? 'bg-green-500 border-green-500' : 'border-gray-300'">
              <view v-if="cartStore.areAllSelected" class="i-mdi-check text-white text-[28rpx]"></view>
            </view>
            <view class="text-[28rpx]">全选</view>
        </view>
        <view class="flex items-center">
          <view class="text-[32rpx] mr-[20rpx]">
            合计: <text class="text-red-500 font-bold">¥{{ cartStore.totalPrice }}</text>
          </view>
          <nut-button type="success"
                  :disabled="cartStore.totalItems === 0"
                  @tap="checkout">
            结算 ({{ cartStore.totalItems }})
          </nut-button>
        </view>
      </view>
    </template>
  </view>
</template>

<style>
.two-line-ellipsis {
  display: -webkit-box;
  -webkit-box-orient: vertical;
  -webkit-line-clamp: 2;
  overflow: hidden;
  text-overflow: ellipsis;
}

.safe-area-bottom {
  padding-bottom: constant(safe-area-inset-bottom);
  padding-bottom: env(safe-area-inset-bottom);
}
</style>
